﻿using Dal.Context;
using Dal.Data.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Dal.Data.Respo
{
    public class Repository<T> : DbContext, IRepository<T> where T : BaseModel
    {

        public DbContext _context { get; set; }
        public DbSet<T> _dbSet { get; set; }

        public Repository(string con)
            : base(con)
        {

        }

        public IEnumerable<T> GetAll()
        {
            return _dbSet;
        }

        public IEnumerable<M> ExecuteStoresProcedure<M>(string sp_name)
        {
            var cmd = Database.Connection.CreateCommand();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            var r = cmd.ExecuteReader();

            return DataReaderMapToList<M>(r);

          
        }

        public void Add(T entity)
        {
            _dbSet.Add(entity);
            _context.SaveChanges();
        }


        private static List<T> DataReaderMapToList<T>(DbDataReader dr)
        {
            List<T> list = new List<T>();
            while (dr.Read())
            {
                var obj = Activator.CreateInstance<T>();
                foreach (PropertyInfo prop in obj.GetType().GetProperties())
                {
                    if (!Equals(dr[prop.Name], DBNull.Value))
                    {
                        prop.SetValue(obj, dr[prop.Name], null);
                    }
                }
                list.Add(obj);
            }
            return list;
        }


    }
}
